package com.yuyou.weixin.util;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

public class BigDecimals {

    public static int compare(BigDecimal b1, BigDecimal b2) {

        long l1 = b1.multiply(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
        long l2 = b2.multiply(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();

        return (int) (l1 - l2);
    }


    public static BigDecimal min(BigDecimal b1, BigDecimal b2) {
        if (compare(b1, b2) < 0) {
            return b1;
        } else {
            return b2;
        }
    }

    public static BigDecimal integer(BigDecimal b) {
        return BigDecimal.valueOf(b.setScale(0, BigDecimal.ROUND_HALF_UP).longValue());
    }

    /*public static void main(String[] args) {
        System.out.println(compare(new BigDecimal(8189.9999991810d), new BigDecimal(8310.00).subtract(new BigDecimal(120).subtract(new BigDecimal("0.00")))));
    }*/

    /**
     * @param amount
     * @param numerator   分子
     * @param denominator 分母
     * @return
     */
    public static BigDecimal calProportion(BigDecimal amount, BigDecimal numerator, BigDecimal denominator) {
        return amount.multiply(numerator.divide(denominator, 10, BigDecimal.ROUND_HALF_UP)).divide(BigDecimal.ONE, 10, BigDecimal.ROUND_HALF_UP);
    }

    public static boolean isZero(BigDecimal value) throws UnsupportedEncodingException {
        return (long) (value.doubleValue() * 100) == 0l;
    }

    public static BigDecimal toFixed2(BigDecimal bigDecimal, int num) {
        if (bigDecimal == null) {
            return BigDecimal.ZERO;
        }
        if (num < 0) {
            throw new IllegalArgumentException("Illegal arguments");
        }
        BigDecimal result = bigDecimal.setScale(num, BigDecimal.ROUND_HALF_UP);
        return result;
    }

    public static String formatBigDecimal(BigDecimal value, String format) {
        if (value == null) {
            return format;
        }
        return new DecimalFormat(format).format(value);
    }
}
